package com.lemon.exam.common.filter;

import com.lemon.exam.common.entity.system.LoginUser;
import com.lemon.exam.common.exception.CustomException;
import com.lemon.exam.common.properties.ConfigProperties;
import com.lemon.exam.common.util.JwtUtil;
import com.lemon.exam.common.util.ResponseUtil;
import com.lemon.exam.common.util.RsaUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 刷新token过滤器
 *
 * @author Lemon
 * @since 2025/3/24 14:30
 */
@Slf4j
@Component
public class RefreshWebFilter implements WebFilter {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private ConfigProperties configProperties;
    @Resource
    private ReactiveAuthenticationManager authenticationManager;

    @Override
    @NonNull
    public Mono<Void> filter(ServerWebExchange exchange, @NonNull WebFilterChain chain) {
        if (!isRefreshRequest(exchange.getRequest())) {
            return chain.filter(exchange);
        }

        return extractRefreshToken(exchange.getRequest())
                .flatMap(this::parseToken)
                .flatMap(this::authenticateUser)
                .flatMap(user -> generateAndSetNewToken(exchange, user))
                .onErrorResume(error -> handleRefreshError(exchange.getResponse(), error));
    }

    /**
     * 判断是否是刷新token请求
     *
     * @param request
     * @return
     */
    private boolean isRefreshRequest(ServerHttpRequest request) {
        return configProperties.getJwt().getRefreshPath().equals(request.getPath().value());
    }

    /**
     * 从请求头中提取刷新token
     *
     * @param request
     * @return
     */
    private Mono<String> extractRefreshToken(ServerHttpRequest request) {
        String refreshToken = request.getHeaders().getFirst(configProperties.getJwt().getRefreshTokenHeader());
        String refreshTokenPrefix = configProperties.getJwt().getRefreshTokenPrefix();

        if (!StringUtils.hasText(refreshToken) || !refreshToken.startsWith(refreshTokenPrefix)) {
            return Mono.error(new CustomException("认证信息错误"));
        }
        return Mono.just(refreshToken.replaceFirst(refreshTokenPrefix, ""));
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    private Mono<Jws<Claims>> parseToken(String token) {
        try {
            return Mono.just(jwtUtil.parseToken(token));
        } catch (ExpiredJwtException e) {
            log.warn("Token过期: {}", e.getMessage());
            return Mono.error(new CustomException("token 过期，请重新登录！"));
        } catch (Exception e) {
            log.error("认证失败: {}", e.getMessage());
            return Mono.error(new CustomException("认证信息错误"));
        }
    }

    /**
     * 认证用户
     *
     * @param claims
     * @return
     */
    private Mono<LoginUser> authenticateUser(Jws<Claims> claims) {
        String username = claims.getPayload().get("username", String.class);
        String password = claims.getPayload().get("password", String.class);

        try {
            String decryptPassword = RsaUtil.getInstance().decryptByPrivateKey(
                    configProperties.getRsa().getPrivateKey(),
                    password);

            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, decryptPassword))
                    .map(auth -> (LoginUser) auth.getPrincipal());
        } catch (Exception e) {
            log.error("密码解密失败:{}", e.getMessage());
            return Mono.error(new CustomException("认证信息错误"));
        }
    }

    /**
     * 生成并设置新的token
     *
     * @param exchange
     * @param user
     * @return
     */
    private Mono<Void> generateAndSetNewToken(ServerWebExchange exchange, LoginUser user) {
        String token = jwtUtil.generateAccessToken(user.getUsername());
        exchange.getResponse().getHeaders().add(HttpHeaders.AUTHORIZATION, configProperties.getJwt().getAccessTokenPrefix() + token);
        return exchange.getResponse().setComplete();
    }

    /**
     * 刷新失败的处理
     *
     * @param response
     * @param error
     * @return
     */
    private Mono<Void> handleRefreshError(ServerHttpResponse response, Throwable error) {
        if (error instanceof CustomException e) {
            return ResponseUtil.err(response, e.getCode(), e.getMessage());
        }
        log.error("刷新处理异常", error);
        return ResponseUtil.err(response, 500, "系统异常");
    }
}
